package com.dc.member.controller;

import com.alibaba.fastjson.JSONObject;
import com.dc.base.BaseResponse;
import com.dc.constant.Constants;
import com.dc.member.constants.WebConstants;
import com.dc.member.controller.req.vo.LoginVo;
import com.dc.member.feign.IMemberLoginServiceFeignPortal;
import com.dc.member.input.dto.UserLoginInpDTO;
import com.dc.web.base.BaseWebController;
import com.dc.web.bean.DcBeanUtils;
import com.dc.web.utils.CookieUtils;
import com.dc.web.utils.RandomValidateCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author: KEYD
 * @Date: 2019/12/29 11:20
 * @Desc: 登录请求
 */
@Controller
public class LoginController extends BaseWebController {

    private static final String MEMBER_LOGIN_FTL = "member/login";  // 跳转到登录页面
    private static final String REDIRECT_INDEX = "redirect:/";    //重定向到首页


    @Autowired
    private IMemberLoginServiceFeignPortal iMemberLoginServiceFeignPortal;

    /**
     * 跳转页面
     *
     * @return
     */
    @GetMapping("/login")
    public String getLogin() {
        return MEMBER_LOGIN_FTL;
    }

    /**
     * 请求接受参数
     *
     * @return
     */
    @PostMapping("/login")
    public String postLogin(@ModelAttribute("loginVo") @Validated LoginVo loginVo, Model model,
                            HttpServletRequest request, HttpServletResponse response,
                            HttpSession httpSession) {
        // 1.图形验证码判断
        String graphicCode = loginVo.getGraphicCode();
        if (!RandomValidateCodeUtil.checkVerify(graphicCode, httpSession)) {
            setErrorMsg(model, "图形验证码不正确!");
            return MEMBER_LOGIN_FTL;
        }
        //2、将vo装换成dto，调用会员登录接口
        UserLoginInpDTO userLoginInpDTO = DcBeanUtils.voToDto(loginVo, UserLoginInpDTO.class);
        userLoginInpDTO.setLoginType(Constants.MEMBER_LOGIN_TYPE_PC);   //防止报错，其实应该根据请求request来改
        userLoginInpDTO.setDeviceInfor(webBrowserInfo(request));
        BaseResponse<JSONObject> login = iMemberLoginServiceFeignPortal.login(userLoginInpDTO);
        if (!isSuccess(login)) {
            setErrorMsg(model, login.getMsg());
            return MEMBER_LOGIN_FTL;
        }
        //3、登录成功，保持会话信息，将token存入到cookie中去，首页读取cookietoken 查询用户信息展示
        JSONObject data = login.getData();
        String token = data.getString("token");
        CookieUtils.setCookie(request, response, WebConstants.LOGIN_TOKEN_COOKIENAME, token);
        return REDIRECT_INDEX;
    }


}
